import React, { ReactElement, useState } from 'react'
import { Col, Card, Tag, Upload, message, Input, Button } from 'antd'
import styles from './AdItem.less'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { connect } from 'umi'
import Cook from 'js-cookie'

interface Props {
    index?: number,
    changeCardInfo: Function,
    changeCardItems: Function
}

function getBase64(img: any, callback: any) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
}

function beforeUpload(file: any) {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
}

function AdItem({ index, changeCardInfo, changeCardItems }: Props): ReactElement {
    const [loading, setLoading] = useState(false)
    const [imageUrl, setImageUrl] = useState("")
    const [val, setVal] = useState("")

    function handleChange(info: any) {
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            changeCardItems({
                index,
                val: info.file.response.url
            })
            // Get this url from response in real world.
            getBase64(info.file.originFileObj, (imageUrl: string) => {
                setLoading(false)
                setImageUrl(imageUrl)
            });
        }
    };
    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    );
    return (
        <Col span={12}>
            <Card className={styles.card} title={<Tag className={styles.p5} color="processing">广告位{index}</Tag>} bordered={false}>
                <div className={ styles.flex }>
                    <span>
                        图片: 
                    </span>
                    <div>
                        <Upload
                            name="file"
                            listType="picture-card"
                            className="avatar-uploader"
                            showUploadList={false}
                            action="/api/upload/ad"
                            // http://localhost:3333/admin/api/upload/ad
                            headers={{
                                Authorization: Cook.get('token')
                            }}
                            beforeUpload={beforeUpload}
                            onChange={handleChange}
                        >
                            {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                        </Upload>
                    </div>
                </div>
                <div className={ styles.flex }>
                    <span>
                        跳转连接: 
                    </span>
                    <div>
                       <Input value={val} onChange={(ev) => {
                           setVal(ev.target.value)
                           changeCardInfo({
                               type: "input",
                               val: ev.target.value,
                               index
                           })
                       }}/>
                    </div>
                </div>
                <div className={ styles.flex }>
                    <span>
                        <Button type="primary" danger>删除</Button>
                    </span>
                </div>
            </Card>
        </Col>
    )
}

const mapState = (state: any) => {
    return {

    }
}

const mapDispatch = (dispatch: any) => {
    return {
        changeCardInfo(info: any) {
            dispatch({ type: "ads/changeCardInfo", info })
        },
        changeCardItems(info: any) {
            dispatch({ type: "ads/changeCardItems", info })
        },
    }
}

export default connect(mapState, mapDispatch)(AdItem)
